package zqwl_1dxrr16

import (
	"context"
	"github.com/tarm/serial"
)

var (
	cmdOnAll  = []byte{0x01, 0x0F, 0x00, 0x00, 0x00, 0x10, 0x02, 0xFF, 0xFF, 0xE3, 0x90}
	cmdOffAll = []byte{0x01, 0x0F, 0x00, 0x00, 0x00, 0x10, 0x02, 0x00, 0x00, 0xE2, 0x20}
)

type Serial struct {
	ctx    context.Context
	cancel context.CancelFunc

	connected bool
	config    *serial.Config
	port      *serial.Port
}

func New(ctx context.Context, config *serial.Config) *Serial {
	ctx, cancel := context.WithCancel(ctx)
	return &Serial{
		ctx:    ctx,
		cancel: cancel,
		port:   nil,
		config: config,
	}
}

func (a *Serial) Open() error {
	port, err := serial.OpenPort(a.config)
	if err != nil {
		return err
	}

	a.port = port
	a.connected = true
	return nil
}

func (a *Serial) OnAll() {
	if !a.connected {
		return
	}
	_, err := a.port.Write(cmdOnAll)
	if err != nil {
		err := a.port.Close()
		if err != nil {
			return
		}
	}
}

func (a *Serial) OffAll() {
	if !a.connected {
		return
	}
	_, err := a.port.Write(cmdOffAll)
	if err != nil {
		err := a.port.Close()
		if err != nil {
			return
		}
	}
}
